import { login } from '@/api/user'
import { defineStore } from 'pinia'
import { jwtDecode } from "jwt-decode";

export interface OptUser {
  userId?: string
  userName?: string
  token?: string
  isAdm: boolean
}
interface MyJwtPayload {
  id: string
  name: string
  isAdm: string
}

export const useUserStore = defineStore('user', {
  state: (): OptUser => {
    const user: OptUser = { isAdm: false }
    try {
      const token = localStorage.getItem("token")
      if (token) {
        const jwt = jwtDecode<MyJwtPayload>(token);
        user.userId = jwt.id
        user.userName = jwt.name
        user.isAdm = jwt.isAdm === 'Y'
        user.token = token
      }
    }
    catch {
      const token = localStorage.removeItem("token")
    }
    return user
  },
  actions: {
    async doLogin(userCode: string, password: string) {
      //这里不能try-catch让调用方来解决
      const token = await login(userCode, password)
      if (token) {
        const jwt = jwtDecode<MyJwtPayload>(token);
        this.userId = jwt.id
        this.token = token
        this.userName = jwt.name
        this.isAdm = jwt.isAdm === 'Y'
        localStorage.setItem("token", this.token)
      }
    },
    doLogout() {
      this.userId = undefined
      this.token = undefined
      this.userName = undefined
      localStorage.removeItem("token");
    },
  },
})